package com.book.lizhi.ui.fragment;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.book.lizhi.AppApplication;
import com.book.lizhi.R;
import com.book.lizhi.adapter.AppAdapter;
import com.book.lizhi.constants.Constants;
import com.book.lizhi.model.BookModel;
import com.book.lizhi.model.ChapterModel;
import com.book.lizhi.read.ReadActivity;

public class ChapterFragment extends Fragment {
	private View mView;
	private ListView mListView;
	private BookModel mBookModel;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mView = View.inflate(getActivity(), R.layout.fragment_chapter, null);
		mBookModel = AppApplication.instance.currentBookModel;
		initUI();
	}

	private void initUI() {
		mListView = (ListView) mView.findViewById(R.id.chapter_listview);

		ChapterAdapter adapter=new ChapterAdapter(getActivity(), mBookModel.chapterModels);
		mListView.setAdapter(adapter);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(getActivity(), ReadActivity.class);
				intent.putExtra(Constants.CURRENT_CHAPTER, position);
				startActivity(intent);
				getActivity().finish();
			}
		});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		if (mView.getParent() != null) {
			((ViewGroup) mView.getParent()).removeView(mView);
		}
		return mView;
	}

	class ChapterAdapter extends AppAdapter {

		public ChapterAdapter(Context context, List<?> list) {
			super(context, list);
		}

		@Override
		public View getView(int position, View convertView, Context context) {
			TextView textView;
			if (convertView == null) {
				convertView = textView = (TextView) View.inflate(getActivity(), R.layout.chapter_item_layout, null);
			} else {
				textView = (TextView) convertView;
			}
			ChapterModel model = (ChapterModel) getItem(position);
			textView.setText(model.name);
			if (model.points.equals("0")) {
				textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
			} else {
				textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.tobuy_icon, 0);
			}
			return convertView;
		}

	}
}
